import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Avatar, 
  Row, 
  Col, 
  Spin, 
  message,
  Descriptions,
  Divider
} from 'antd';
import { UserOutlined, MailOutlined, PhoneOutlined } from '@ant-design/icons';
import api from '../services/api';

const ProfilePage = () => {
  const [userInfo, setUserInfo] = useState(null);
  const [loading, setLoading] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [form] = Form.useForm();

  // 获取当前用户信息
  const fetchUserInfo = async () => {
    setLoading(true);
    try {
      const response = await api.get('/users/me');
      setUserInfo(response.data);
      form.setFieldsValue(response.data);
    } catch (error) {
      console.error('获取用户信息失败:', error);
      message.error('获取用户信息失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
  }, []);

  const handleSave = async (values) => {
    setLoading(true);
    try {
      const response = await api.put(`/users/${userInfo.id}`, values);
      setUserInfo(response.data);
      setEditMode(false);
      message.success('个人信息更新成功');
    } catch (error) {
      console.error('更新个人信息失败:', error);
      message.error('更新个人信息失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.setFieldsValue(userInfo);
    setEditMode(false);
  };

  if (loading && !userInfo) {
    return (
      <div style={{ textAlign: 'center', marginTop: '100px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto' }}>
      <h2>个人中心</h2>
      
      <Row gutter={24}>
        <Col span={8}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Avatar 
                size={120} 
                icon={<UserOutlined />}
                style={{ backgroundColor: '#1890ff', marginBottom: '16px' }}
              />
              <h3>{userInfo?.username}</h3>
              <p style={{ color: '#666' }}>{userInfo?.email}</p>
            </div>
          </Card>
        </Col>
        
        <Col span={16}>
          <Card 
            title="基本信息" 
            extra={
              !editMode ? (
                <Button type="primary" onClick={() => setEditMode(true)}>
                  编辑
                </Button>
              ) : null
            }
          >
            {!editMode ? (
              <Descriptions column={1}>
                <Descriptions.Item label="用户名">
                  {userInfo?.username}
                </Descriptions.Item>
                <Descriptions.Item label="邮箱">
                  {userInfo?.email}
                </Descriptions.Item>
                <Descriptions.Item label="角色">
                  {userInfo?.role === 'admin' ? '管理员' : 
                   userInfo?.role === 'engineer' ? '工程师' : '客户'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {userInfo?.created_at && new Date(userInfo.created_at).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="最后更新">
                  {userInfo?.updated_at && new Date(userInfo.updated_at).toLocaleString()}
                </Descriptions.Item>
              </Descriptions>
            ) : (
              <Form
                form={form}
                layout="vertical"
                onFinish={handleSave}
              >
                <Form.Item
                  name="username"
                  label="用户名"
                  rules={[{ required: true, message: '请输入用户名' }]}
                >
                  <Input prefix={<UserOutlined />} placeholder="用户名" />
                </Form.Item>
                
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入有效的邮箱地址' }
                  ]}
                >
                  <Input prefix={<MailOutlined />} placeholder="邮箱" />
                </Form.Item>
                
                <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: '8px' }}>
                    保存
                  </Button>
                  <Button onClick={handleCancel}>
                    取消
                  </Button>
                </Form.Item>
              </Form>
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProfilePage;